﻿using System;
using System.Collections.Generic;

namespace Gonte.Types
{
    /// <summary>
    /// An object that can be created dynamically
    /// </summary>
    public class DynamicObject
    {
        #region Constructors

        internal DynamicObject(DynamicClass @class)
        {
            ExceptionThrower.ThrowWhenNull("class", @class);
            class_ = @class;

            // Initialize the fields
            foreach (DynamicFieldInfo fieldInfo in class_.FieldsInfo.Values)
            {
                fields_.Add(fieldInfo.Name, fieldInfo.InitialValue);
            }
        } 

        #endregion

        public void SetValue(string fieldName, Object value)
        {
            // If the field is not in the class throw an exception
            ExceptionThrower.ThrowWhenNot(class_.FieldsInfo.ContainsKey(fieldName), 
                string.Format("Dynamic field of name: '{0}' does not exist in dynamic class: '{1}'", fieldName, class_.Name));

            fields_[fieldName] = value;
        }

        public Object GetValue(string fieldName)
        {
            // If the field is not in the class throw an exception
            ExceptionThrower.ThrowWhenNot(class_.FieldsInfo.ContainsKey(fieldName),
                string.Format("Field of name: '{0}' does not exist in class: '{1}'", fieldName, class_.Name));

            if (!fields_.ContainsKey(fieldName))
            {
                fields_[fieldName] = class_.FieldsInfo[fieldName].InitialValue;
            }

            return fields_[fieldName];
        }

        #region Properties

        //public Dictionary<string, Object> Fields
        //{
        //    get { return fields_; }
        //    set { fields_ = value; }
        //} 

        #endregion

        #region Fields

        private readonly DynamicClass class_;
        private Dictionary<string, Object> fields_ = new Dictionary<string, Object>(); 

        #endregion

        

    }
}
